package com.example.client;

import javafx.application.Platform;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;

public class MyClient implements Runnable{
    TextField address;
    TextField date;
    TextField time;
    TextField temperature;
    TextField humidity;
    TextField co2;
    TextField lux;
    Button button;


    public MyClient(){//默认构造方法
        super();
    }

    public MyClient(TextField date, TextField time, TextField temperature,TextField humidity,TextField co2,TextField lux, TextField address,Button button){//含参构造方法
        super();
        this.address = address;
        this.date = date;
        this.time = time;
        this.temperature = temperature;
        this.humidity = humidity;
        this.co2 = co2;
        this.lux = lux;
        this.button = button;
    }

    @Override
    public void run(){
        try{
            //初始化先进行socket连接
            Socket socket = new Socket("127.0.0.1",8888);
            OutputStream out = socket.getOutputStream();
            PrintWriter printWriter = new PrintWriter(out);

            //绑定发送数据按钮（sendButton）点击事件，在输入数据并点击后获取时间、温度、信息发送到服务器端
            button.setOnAction(event -> {
                System.out.println("成功点击发送数据按钮");

                Timer timer = new Timer();//定时器
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        Platform.runLater(new Runnable() {
                            @Override
                            public void run() {
                                printWriter.write(address.getText() +"\r" + date.getText() + "\r" + time.getText() + "\r" + temperature.getText() + "\r" + humidity.getText() + "\r" + co2.getText()+ "\r" + lux.getText()+"\r\r");
                                printWriter.flush();
                            }
                        });
                    }
                },100,2000);


            });
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
